/*
 *		source/mainview/mainview.js - Main View
 */

/* tazLoader - Download manager
 * Copyright (C) 2011 Timo Tegtmeier
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 3
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

enyo.kind({
	name:	"MainView",
	kind:	"VFlexBox",

	fileName:		"",
	files:			[],

	components:	[{
		kind:		"PageHeader",
		className:	"enyo-toolbar-light",
		components: [{
			kind:		"Image",
			style:		"margin: 0px; padding: 0px;",
			src:		"../../icon48.png"
		}, {
			kind:		"Control",
			style:		"margin-left: 20px;",
			content:	"tazLoader"
		}]
	}, {
		kind:	"SlidingPane",
		flex:	1,
		components:	[{
			kind:		"SlidingView",
			width:		"320px",
			LayoutKind:	"VFlexLayout",
			components:[{
				kind:		"VirtualList",
				name:		"list",
				flex:		1,
				onSetupRow:	"setupRow",
				components:	[{
					name:		"item",
					kind:		"SwipeableItem",
					onConfirm:	"deleteFile",
					onclick:	"openFile",
					components:	[{
						kind:	"HFlexBox",
						align:	"center",
						components: [{
							kind:	"Image",
							src:	"../../icon48.png",
							style:	"margin-right: 20px"
						}, {
							kind:	"Control",
							flex:	1,
							components: [{
								content:	$L("Issue of"),
								style:		"color: gray; font-size: 18px"
							}, {
								name:	"fileEntry",
								style:	"font-weight: bold; font-size: 21px;"
							}]
						}]
					}]
				}]
			}, {
				kind:	"Toolbar"
			}]
		}, {
			kind:		"SlidingView",
			flex:		1,
			LayoutKind:	"VFlexLayout",
			components:	[{
				kind:		"Control",
				style:		"margin: 20px",
				flex:		1,
				components:	[{
					kind:		"RowGroup",
					caption:	$L("Credentials"),
					components:	[{
						name:	"username",
						kind:	"Input",
						hint:	$L("User name")
					}, {
						name:	"password",
						kind:	"PasswordInput",
						hint:	$L("Password")
					}]
				}, {
					kind:		"RowGroup",
					caption:	$L("Automatic Download"),
					components:	[{
						name:		"autoEnabled",
						kind:		"ToggleItem",
						caption:	$L("Enabled"),
						onChange:	"autoChanged"
					}, {
						name:		"autoTime",
						kind:		"TimeItem",
						caption:	$L("Time"),
						onChange:	"autoChanged"
					}]
				}, {
					kind:		"RowGroup",
					caption:	$L("Manual Download"),
					components:	[{
						name:		"date",
						kind: 		"DateItem",
						caption: 	$L("Issue to download")
					}, {
						name:		"openAfterDownload",
						kind:		"ToggleItem",
						caption:	$L("Open after download")
					}]
				}, {
					name:		"downloadButton",
					kind:		"ActivityButton",
					caption:	$L("Download now"),
					onclick:	"downloadTaz"
				}, {
					name:		"progressbar",
					kind:		"ProgressBar",
					showing:	false
				}]
			}, {
				kind:		"Toolbar",
				components:	[{
					kind:	"GrabButton"
				}]
			}]
		}]
	}, {
		kind:		"ApplicationEvents",
		onUnload:	"saveSettings"
	},  {
		name:		"downloader",
		kind:		"PalmService",
		service:	"palm://com.palm.downloadmanager/",
		subscribe:	true,
		method:		"download",
		onSuccess:	"downloadSuccess",
		onFailure:	"downloadFailed"
	}, {
		name:		"fileService",
		kind:		"PalmService",
		subscribe:	true,
		service:	"palm://com.tegistuff.app.tazloader.service/"
	}, {
		kind: 		"Dialog",
		name:		"errorDialog",
		components: [{
			allowHtml:	true,
			style:		"margin: 25px",
			content: 	$L("<b>Downloading issue failed.</b><br /> Check your credentials. Maybe the issue is not yet available.")
		}, {
			kind: 	"HFlexBox",
			pack: "center",
			components: [{
	            kind:		"Button",
				caption:	$L("OK"),
				onclick:	"closeDialog"
			}]
		}]
	}, {
		kind:					"AppMenu",
		components:				[{
			kind:				"EditMenu"
		}, {
			caption:			$L("License"),
			onclick:			"openLicense"
		}, {
			caption:			$L("Help"),
			onclick:			"openHelp"
		}]
	}, {
		name:		"licenseDialog",
		kind:		"LicenseDialog"
	}, {
		name:		"helpDialog",
		kind:		"HelpDialog"
	}],

	autoChanged: function(sender) {
		this.saveSettings();
	},

	setupRow: function(sender, rowIndex) {
		if((rowIndex < 0) || (rowIndex >= this.files.length)) {
			return false;
		}

		var file = this.files[rowIndex].replace(/(\d{4})_(\d{2})_(\d{2}).*/, "$3.$2.$1");
		this.$.fileEntry.setContent(file);

		return true;
	},

	openFile: function(sender, event) {
		enyo.application.openFile(enyo.application.kDownloadPath + this.files[event.rowIndex]);
	},

	deleteFile: function(sender, rowIndex) {
		this.$.fileService.call({
			path:	enyo.application.kDownloadPath + this.files[rowIndex]
		}, {
			method:		"deletefile",
			onSuccess:	"refreshFiles"
		});
	},

	closeDialog: function(sender, event) {
		this.$.errorDialog.close();
	},

	saveSettings: function(sender, event) {
		var cookie = {
			username:		this.$.username.getValue(),
			password:		this.$.password.getValue(),
			autoOpen:		this.$.openAfterDownload.getValue(),
			autoEnabled:	this.$.autoEnabled.getValue(),
			autoTimeMin:	this.$.autoTime.getValue().getMinutes(),
			autoTimeHour:	this.$.autoTime.getValue().getHours()
		}
		enyo.application.saveSettings(cookie);
	},

	setUIState: function(state) {
		this.$.downloadButton.setActive(state);
		this.$.downloadButton.setDisabled(state);
		this.$.username.setDisabled(state);
		this.$.password.setDisabled(state);
		this.$.openAfterDownload.setDisabled(state);
		this.$.date.setDisabled(state);
	},

	downloadTaz: function(sender, event) {
		this.setUIState(true);
		this.saveSettings();

		var params = enyo.application.getDownloadDetailsFromDate(this.$.date.getValue());
		this.fileName = params.fileName;
		this.$.downloader.call({
             target: 					params.url,
             mime: 						"application/pdf",
             targetDir : 				enyo.application.kDownloadPath,
             targetFilename : 			this.fileName,
             keepFilenameOnRedirect:	true,
             canHandlePause: 			true
		});
	},

	downloadSuccess: function(sender, response) {
		if(response.completed) {
			if(response.amountReceived < 128 * 1024) {
				this.$.fileService.call({
					path:	enyo.application.kDownloadPath + this.fileName
				}, {
					method:		"deletefile",
					onSuccess:	"downloadFailed",
					onFailure:	"downloadFailed"
				});
				return;
			}
			this.refreshFiles();
			this.$.fileService.call({
				path:	enyo.application.kDownloadPath + this.fileName
			}, {
				method:		"pathexists",
				onSuccess:	"downloadComplete",
				onFailure:	"downloadFailed"
			});
		} else {
			if(!this.$.progressbar.getShowing()) {
				this.$.progressbar.setMinimum(0);
				this.$.progressbar.setMaximum(response.amountTotal);
				this.$.progressbar.setPosition(response.amountReceived);
				this.$.progressbar.show();
			} else  {
				this.$.progressbar.setMaximum(response.amountTotal);
				this.$.progressbar.setPosition(response.amountReceived);
			}
		}
	},

	downloadComplete: function(sender, response) {
		if(!response.exists) {
			this.$.errorDialog.open();
		} else {
			if(this.$.openAfterDownload.getValue()) {
				enyo.asyncMethod(this, function() {
					enyo.application.openFile(enyo.application.kDownloadPath + this.fileName);
				});
			}
		}
		this.setUIState(false);
		this.$.progressbar.hide();
	},

	downloadFailed: function(sender, response) {
		this.setUIState(false);
		this.$.progressbar.hide();
		this.$.errorDialog.open();
	},

	gotFiles: function(sender, response) {
		this.files = response.files;
		this.$.list.refresh();
	},

	refreshFiles: function() {
		this.$.fileService.call({
			path:	enyo.application.kDownloadPath
		}, {
			method:		"scandir",
			onSuccess:	"gotFiles"
		});
	},

	openHelp: function() {
		enyo.asyncMethod(this, function() {
			this.$.helpDialog.openAtCenter();
		});
	},

	openLicense: function() {
		enyo.asyncMethod(this, function() {
			this.$.licenseDialog.openAtCenter();
		});
	},

	create: function() {
		this.inherited(arguments);

		enyo.keyboard.setResizesWindow(false);

		var settings = enyo.application.getSettings();
		this.$.username.setValue(settings.username);
		this.$.password.setValue(settings.password);
		this.$.openAfterDownload.setValue(settings.autoOpen);

		this.$.autoEnabled.setValue(settings.autoEnabled);

		var d = new Date();
		d.setMinutes(settings.autoTimeMin);
		d.setHours(settings.autoTimeHour);
		this.$.autoTime.setValue(d);

		this.refreshFiles();
	}
});
